package com.banmao.mall.controller.admin;

import com.alibaba.druid.util.StringUtils;
import com.banmao.mall.model.bo.admin.market.*;
import com.banmao.mall.model.pojo.Category;
import com.banmao.mall.model.pojo.Issue;
import com.banmao.mall.model.pojo.Keyword;
import com.banmao.mall.model.vo.BaseRespVO;
import com.banmao.mall.model.vo.admin.market.*;
import com.banmao.mall.service.admin.MarketService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/admin")
public class MarketController {

    @Autowired
    MarketService marketService;


    // 获取行政区域
    @RequiresPermissions("admin:region:list")
    @RequestMapping("/region/list")
    public BaseRespVO regionList() {
        List<ProvinceVO> provinceVOList = marketService.regionList();

        return BaseRespVO.ok(provinceVOList);
    }


    // 获取品牌制造商
    @RequestMapping("/brand/list")
    @RequiresPermissions("admin:brand:list")
    public BaseRespVO brandList(BrandListBO brandListBO) {

        if (!StringUtils.isEmpty(brandListBO.getId())) {
            Integer.parseInt(brandListBO.getId());
        }

        BrandListVO brandListVO = marketService.brandList(brandListBO);

        return BaseRespVO.ok(brandListVO);
    }


    // 图片上传
    @RequestMapping("/storage/create")
    @RequiresPermissions("admin:storage:create")
    public BaseRespVO storageCreate(@RequestParam("file") MultipartFile multipartFile, HttpServletRequest request) {

        FileUploadVO fileUploadVO = marketService.fileUpload(multipartFile, request);
        if (fileUploadVO == null) {
            return BaseRespVO.error("上传失败啦", 401);
        }

        return BaseRespVO.ok(fileUploadVO);
    }


    // 更新品牌商信息
    @RequestMapping("/brand/update")
    @RequiresPermissions("admin:brand:update")
    public BaseRespVO brandUpdate(@Validated @RequestBody BrandBO brandBO, BindingResult bindingResult) {

        if (bindingResult.hasErrors()) {
            String wrongParamMessage = wrongParamMessage(bindingResult);
            return BaseRespVO.error(wrongParamMessage, 401);
        }

        BrandVO brandVO = marketService.brandUpdate(brandBO);
        if (brandVO == null) {
            return BaseRespVO.error("更新失败", 401);
        }

        return BaseRespVO.ok(brandVO);
    }

    private String wrongParamMessage(BindingResult bindingResult) {

        FieldError fieldError = bindingResult.getFieldError();

        if (fieldError != null) {
            return "【错误】" + fieldError.getField() + fieldError.getDefaultMessage();
        }

        return "参数值不正确";
    }


    // 添加品牌商信息
    @RequestMapping("/brand/create")
    @RequiresPermissions("admin:brand:create")
    public BaseRespVO brandCreate(@Validated @RequestBody BrandBO brandBO, BindingResult bindingResult) {

        if (bindingResult.hasErrors()) {
            String message = wrongParamMessage(bindingResult);
            return BaseRespVO.error(message, 401);
        }

        BrandVO brandVO = marketService.brandCreate(brandBO);
        if (brandVO == null) {
            return BaseRespVO.error("添加失败", 401);
        }

        return BaseRespVO.ok(brandVO);
    }


    // 删除品牌商信息（逻辑删除）
    @RequestMapping("/brand/delete")
    @RequiresPermissions("admin:brand:delete")
    public BaseRespVO brandDelete(@RequestBody BrandBO brandBO) {
        int result = marketService.brandDelete(brandBO);

        if (result == 0) {
            return BaseRespVO.error("删除失败", 401);
        }

        return BaseRespVO.ok(null);
    }


    // 获取商品类目l1
    @RequestMapping("/category/l1")
    public BaseRespVO categoryL1() {
        List<CategoryL1VO> categoryL1VOS = marketService.categoryL1();

        return BaseRespVO.ok(categoryL1VOS);
    }

    // 获取所有商品类目
    @RequestMapping("/category/list")
    @RequiresPermissions("admin:category:list")
    public BaseRespVO categoryList() {
        List<CategoryVO> categoryVOList = marketService.selectAllCategory();

        return BaseRespVO.ok(categoryVOList);
    }


    // 添加类目
    @RequestMapping("/category/create")
    @RequiresPermissions("admin:category:create")
    public BaseRespVO categoryCreate(@RequestBody @Validated CategoryBO categoryBO) {

        if ("L2".equals(categoryBO.getLevel()) && categoryBO.getPid() == 0) {
            return BaseRespVO.error("请给二级类目选择一个父类目", 401);
        }

        Category category = marketService.categoryCreate(categoryBO);
        if (category == null) {
            return BaseRespVO.error("插入失败", 401);
        }

        return BaseRespVO.ok(category);
    }

    // 更改类目
    @RequestMapping("/category/update")
    @RequiresPermissions("admin:category:update")
    public BaseRespVO categoryUpdate(@RequestBody @Validated CategoryBO categoryBO) {

        // 不应该允许一级类目更改成自己的二级目录
        if (categoryBO.getId().equals(categoryBO.getPid())) {
            return BaseRespVO.error("不允许将一级目录更改为自己的二级目录", 401);
        }

        int result = marketService.categoryUpdate(categoryBO);
        if (result == 0) {
            return BaseRespVO.error("更改失败！", 401);
        }

        return BaseRespVO.ok(null);
    }


    // 删除类目（逻辑删除）
    @RequestMapping("/category/delete")
    @RequiresPermissions("admin:category:delete")
    public BaseRespVO categoryDelete(@RequestBody CategoryBO categoryBO) {

        int result = marketService.categoryDelete(categoryBO);
        if (result == 0) {
            return BaseRespVO.error("删除失败", 401);
        }

        return BaseRespVO.ok(null);
    }

    //根据条件获取订单列表
    @RequestMapping("/order/list")
    @RequiresPermissions("admin:order:list")
    public BaseRespVO orderList(OrderListBO orderListBO) {
        //Request URL: http://182.92.235.201:8083/admin/order/list?
        // page=1&limit=20&orderStatusArray=103&sort=add_time&order=desc&userId=2
        // &orderSn=20210424759808
        //Request Method: GET
        //响应体：
        //{
        //    "errno": 0,
        //    "data": {
        //        "total": 1,
        //        "items": [{
        //            "id": 24,
        //            "userId": 1,
        //            "orderSn": "20210424759808",
        //            "orderStatus": 103,
        //            "consignee": "张松",
        //            "mobile": "18566549962",
        //            "address": "安徽省 合肥市 瑶海区 碧桂园",
        //            "message": "",
        //            "goodsPrice": 3999,
        //            "freightPrice": 0,
        //            "couponPrice": 0,
        //            "integralPrice": 0,
        //            "grouponPrice": 0,
        //            "orderPrice": 3999,
        //            "actualPrice": 3999,
        //            "comments": 0,
        //            "endTime": "2021-04-24 12:21:31",
        //            "addTime": "2021-04-24 11:42:22",
        //            "updateTime": "2021-04-24 12:21:31",
        //            "deleted": false
        //        }]
        //    },
        //    "errmsg": "成功"
        //}
        OrderListVO orderListVO = marketService.getOrderList(orderListBO);
        return BaseRespVO.ok(orderListVO);
    }

    //查看单个订单详情
    @RequestMapping("order/detail")
    @RequiresPermissions("admin:order:read")
    public BaseRespVO orderDetail(Integer id) {
        /**
         * 返回的OrderDetailVO类中的属性各自包含的属性是相应pojo的一部分，为方便，直接用pojo。
         */
        OrderDetailVO orderDetailVO = marketService.getOrderDetailById(id);
        return BaseRespVO.ok(orderDetailVO);
    }

    //订单退款
    @RequestMapping("order/refund")
    @RequiresPermissions("admin:order:refund")
    public BaseRespVO orderRefund(@RequestBody OrderRefundBO orderRefundBO) {
        //Request URL: http://182.92.235.201:8083/admin/order/refund
        //请求体：{"orderId":10,"refundMoney":77}
        int error = marketService.orderRefund(orderRefundBO);
        if (error != 0) {
            return BaseRespVO.error("数据库正在升级", 500);
        }
        return BaseRespVO.ok(null);
    }

    //订单发货
    @RequestMapping("order/ship")
    @RequiresPermissions("admin:order:ship")
    public BaseRespVO orderShip(@RequestBody OrderShipBO orderShipBO) {
        //Request URL: http://localhost:8083/admin/order/ship
        //请求体：{"orderId":2,"shipChannel":"东风","shipSn":"47"}
        int error = marketService.orderShip(orderShipBO);
        if (error != 0) {
            return BaseRespVO.error("数据库正在升级", 500);
        }
        return BaseRespVO.ok(null);
    }

    //查找通用问题列表
    @RequestMapping("issue/list")
    @RequiresPermissions("admin:issue:list")
    public BaseRespVO issueList(IssueListBO issueListBO) {
        //Request URL: http://182.92.235.201:8083/admin/issue/list?page=1&limit=20
        // &question=%E5%AF%B9%E5%AF%B9%E5%AF%B91222&sort=add_time&order=desc
        //响应体：
        // {
        //    "errno": 0,
        //    "data": {
        //        "total": 1,
        //        "items": [{
        //            "id": 16,
        //            "question": "对对对1222",
        //            "answer": "对对对1",
        //            "addTime": "2021-05-10 17:48:48",
        //            "updateTime": "2021-05-10 20:57:18",
        //            "deleted": false
        //        }]
        //    },
        //    "errmsg": "成功"
        //}
        IssueListVO issueListVO = marketService.getIssueList(issueListBO);
        return BaseRespVO.ok(issueListVO);
    }

    //添加通用问题
    @RequestMapping("issue/create")
    @RequiresPermissions("admin:issue:create")
    public BaseRespVO issueCreate(@RequestBody IssuecreateBO issuecreateBO) {
        Issue issue = marketService.issueCreate(issuecreateBO);
        return BaseRespVO.ok(issue);

    }

    //编辑通用问题
    @RequestMapping("issue/update")
    @RequiresPermissions("admin:issue:update")
    public BaseRespVO issueUpdate(@RequestBody Issue issue) {
        //请求体和响应体为pojo，故无须新设bo和vo
        Issue issueUpdate = marketService.issueUpdate(issue);
        return BaseRespVO.ok(issueUpdate);
    }

    //删除通用问题
    @RequestMapping("issue/delete")
    @RequiresPermissions("admin:issue:delete")
    public BaseRespVO issueDelete(@RequestBody Issue issue) {
        //请求体和响应体为pojo，故无须新设bo和vo
        int error = marketService.issueDelete(issue);
        if (error != 0) {
            return BaseRespVO.error("数据库在升级。。",error);
        }
        return BaseRespVO.ok(null);
    }

    //获取关键词列表
    @RequestMapping("keyword/list")
    @RequiresPermissions("admin:keyword:list")
    public BaseRespVO keywordList(KeywordListBO keywordListBO) {
        KeywordListVO keywordListVO = marketService.getKeywordList(keywordListBO);
        return BaseRespVO.ok(keywordListVO);
    }

    //添加关键词
    @RequestMapping("keyword/create")
    @RequiresPermissions("admin:keyword:create")
    public BaseRespVO keywordCreate(@RequestBody Keyword keyword) {
        //用pojo代替vo
        int error = marketService.keywordCreate(keyword);
        if (error != 0) {
            return BaseRespVO.error("数据库在升级。。",error);
        }
        return BaseRespVO.ok(keyword);

    }

    //编辑关键字
    @RequestMapping("keyword/update")
    @RequiresPermissions("admin:keyword:update")
    public BaseRespVO keywordUpdate(@RequestBody Keyword keyword) {
        //请求体和响应体为pojo，故无须新设bo和vo
        int error = marketService.keywordUpdate(keyword);
        if (error != 0) {
            return BaseRespVO.error("数据库在升级。。",error);
        }
        return BaseRespVO.ok(keyword);
    }

    //删除关键字
    @RequestMapping("keyword/delete")
    @RequiresPermissions("admin:keyword:delete")
    public BaseRespVO keywordDelete(@RequestBody Keyword keyword) {
        //请求体和响应体为pojo，故无须新设bo和vo
        int error = marketService.keywordDelete(keyword);
        if (error != 0) {
            return BaseRespVO.error("数据库在升级。。",error);
        }
        return BaseRespVO.ok(null);
    }
}













